#pragma once

#include "muduo/net/TcpConnection.h"
#include "Connection.hpp"
#include <unordered_map>
#include <mutex>

namespace micromq
{
    class ConnectionManager
    {
    public:
        using ptr = std::shared_ptr<ConnectionManager>;
    public:
        ConnectionManager()
        {}

        void addConnection(const VirtualHost::ptr& host, const ConsumerManager::ptr& consumerManager, 
            const muduo::net::TcpConnectionPtr& conn, const ProtobufCodecPtr& codec)
        {
            std::unique_lock<std::mutex> lock(_mtx);
            if(_conns.find(conn) != _conns.end()) return;
            Connection::ptr connection = std::make_shared<Connection>(host, consumerManager, conn, codec);
            _conns[conn] = connection;
        }

        void removeConnection(const muduo::net::TcpConnectionPtr& conn)
        {
            std::unique_lock<std::mutex> lock(_mtx);
            _conns.erase(conn);
        }

        Connection::ptr getConnection(const muduo::net::TcpConnectionPtr& conn)
        {
            std::unique_lock<std::mutex> lock(_mtx);
            auto it = _conns.find(conn);
            if(it == _conns.end()) return nullptr;
            return it->second;
        }
        
        ~ConnectionManager()
        {}
    private:
        std::mutex _mtx;
        std::unordered_map<muduo::net::TcpConnectionPtr, Connection::ptr> _conns; //TcpConnection和Connection是一一对应的
    };
}